import { itemConfig } from '@/components/form-item/itemConfig';
import { basicComponentConfig } from '@/components/form-basic/basicComponentConfig';
import { containerConfig } from '@/components/form-container/containerConfig'

const formType = "designer";

// 合并行容器和表单项配置
const containerWidgetList = containerConfig.map(item => ({
    ...item,
    isContainer: true
}));
const itemWidgetList = itemConfig.map(item => ({
    ...item,
    isFormItem: true
}));
const basicComponentList = basicComponentConfig;

const widgetJsonList = [
    ...containerWidgetList,
    ...itemWidgetList,
    ...basicComponentList
]

// 通过type获取组件的json配置信息
const getWidgetJsonByType = (type) => {
    const result = widgetJsonList.find(item => item.type === type);
    if( result ) {
        return result;
    } else {
        return null;
    }
}



// 深度克隆组件
const cloneComponent = (component, widgetList) => {
    const cloned = deepClone(component)
    cloned.id = generateUniqueId(component.id, widgetList)
    return cloned
}

const deepClone = (obj) => {
    if (obj === null || typeof obj !== 'object') return obj
    if (Array.isArray(obj)) return obj.map(deepClone)

    const cloned = {}
    for (const key in obj) {
        cloned[key] = deepClone(obj[key])
    }
    return cloned
}

const generateUniqueId = (id, widgetList) => {
    let newId
    do {
        const randomDigits = Math.floor(1000 + Math.random() * 9000)
        newId = `${id}${randomDigits}`
    } while (!isUniqueId(newId, widgetList))
    return newId
}

/**
 * 判断全局id是否重复
 */
const isUniqueId = (id, widgetList) => {
    const stack = [...widgetList]
    while (stack.length) {
        const current = stack.pop()
        if (current.id === id) return false
        if (Array.isArray(current.children)) {
            stack.push(...current.children)
        }
    }
    return true
}

/**
 * 检查组件绑定字段 fieldId 是否重复
 * @param {string} fieldId - 要检测的字段 ID
 * @param {Array} widgetList - 组件树
 * @param {string|null} subFormId - 子表 ID（可选），用于限定作用域
 * @returns {boolean} - 是否唯一
 */
const isFormFieldIdUnique = (fieldId, widgetList, subFormId = null) => {
    const stack = [...widgetList]
    while (stack.length) {
        const current = stack.pop()
        if (subFormId) {// 传入子表时，只判断同一个子表内的id是否重复
            if (current.fieldId && current.fieldId === fieldId && current.subFormId && current.subFormId == subFormId) return false
        } else {// 不传入时只检查与不是子表字段的id是否重复
            if (current.fieldId && current.fieldId === fieldId && !current.subFormId) return false
        }
        if (Array.isArray(current.children)) {
            stack.push(...current.children)
        }
    }
    return true
}

const getWidgetById = (list, id) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        if (item.id === id) {
            return item;
        } else if (item.children && item.children.length > 0) {
            const widget = getWidgetById(item.children, id);
            if (widget) return widget;
        }
    }
    return null;
};

// 通过fieldId获取子表单
const getSubFormWidgetByFieldId = (list, fieldId) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        if (item.fieldId === fieldId && item.isSubForm ) {
            return item;
        } else if ( item.children && item.children.length > 0 ) {//只在容器组件中查找
            const widget = getSubFormWidgetByFieldId(item.children, fieldId);
            if (widget) return widget;
        }
    }
    return null;
};

// 渲染不同类型的组件
const renderComponent = (config) => {
    if (!config?.type) return 'div';
    if(config.isCustomWidget) {
        return 'CustomWidget';
    }
    const typeName = config.type.charAt(0).toUpperCase() + config.type.slice(1);
    return `${typeName}Widget`;
};

export default {
    formType,
    containerWidgetList,
    itemWidgetList,
    basicComponentList,
    getWidgetById,
    getSubFormWidgetByFieldId,
    cloneComponent,
    renderComponent,
    generateUniqueId,
    isUniqueId,
    isFormFieldIdUnique,
    getWidgetJsonByType
}